package com.base.commons.tools.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;

/**
 * Created by Carr on 2018/6/20 .
 */
@Slf4j
public class FileUtil {


    /**
     * 得到字节流 数组大小
     */
    public static byte[] readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }

    /**
     * 项目文件根路径
     * @return  rootPath
     */
    public static String rootPath() {
        return System.getProperty("user.dir");
    }

    /**
     * PDF文件和图片上传腾讯云后删除本地文件
     * @param path
     */
    private void deleteFile(String path) {
        File file = new File(path);
        if (file.exists()){
            file.delete();
        }
    }

    /**
     * 根据目录删除文件,保留目录
     * @param path
     */
    public static boolean deleteDir(String path) {
        File file = new File(path);
        if (!file.exists()) {// 判断是否待删除目录是否存在
            return false;
        }
        String[] content = file.list();// 取得当前目录下所有文件和文件夹
        for (String name : content) {
            File temp = new File(path, name);
            if (temp.isDirectory()) {// 判断是否是目录
                deleteDir(temp.getAbsolutePath());// 递归调用，删除目录里的内容
                temp.delete();
            } else {
                temp.delete();// 删除文件
            }
        }
        return true;
    }


    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful.
     *                 If a deletion fails, the method stops attempting to
     *                 delete and returns "false".
     */
    public static  boolean delDir(String dir) {
        File file = new File(dir);
        boolean delete ;
        if (file.isDirectory()) {
            String[] children = file.list();
            if(children.length>0){
                /**递归删除目录中的子目录下*/
                for (int i=0; i<children.length; i++) {
                    boolean success = delDir(file.getPath()+"/"+children[i]);
                    if (!success) {
                        return false;
                    }
                }
            }
            delete = file.delete();
            log.info("删除目录"+delete);
        }else {
            delete = file.delete();
            log.info("删除文件"+delete);
        }
        return delete;
    }

}
